package com.ruoyi.back.service.impl

import cn.hutool.core.date.DateField
import cn.hutool.core.date.DateUtil
import com.baomidou.mybatisplus.extension.kotlin.KtQueryWrapper
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl
import com.baomidou.shaun.core.context.ProfileHolder
import com.ruoyi.app.common.id
import com.ruoyi.back.domain.ChannelManager
import com.ruoyi.back.domain.UserChannelFunction
import com.ruoyi.back.domain.UserChannelFunctionTask
import com.ruoyi.back.mapper.UserChannelFunctionMapper
import com.ruoyi.back.mapper.UserChannelFunctionTaskMapper
import com.ruoyi.back.service.ChannelFunctionService
import com.ruoyi.back.service.ChannelManagerService
import com.ruoyi.back.service.UserChannelFunctionService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import java.util.*

@Service
class UserChannelFunctionServiceImpl : ServiceImpl<UserChannelFunctionMapper, UserChannelFunction>(),
    UserChannelFunctionService {

    @Autowired
    private lateinit var channelManagerService: ChannelManagerService

    @Autowired
    private lateinit var channelFunctionService: ChannelFunctionService

    @Autowired
    private lateinit var userChannelFunctionTaskMapper: UserChannelFunctionTaskMapper

    override fun initUserChannelFunction(channelCode: Long) {

        channelManagerService.getOne(
            KtQueryWrapper(ChannelManager::class.java)
                .eq(ChannelManager::name, channelCode)
        )
            ?.let { channelManager ->
                channelFunctionService.getFunctionByChannel(channelManager.id!!)
                    .takeIf { it.isNotEmpty() }
                    ?.run {
                        forEach {
                            it.delay?.let { delayTime ->
                                userChannelFunctionTaskMapper.insert(UserChannelFunctionTask().apply {
                                    userId = ProfileHolder.getProfile().id.toLong()
                                    channelId = it.channelId
                                    functionId = it.functionId
                                    executeTime = DateUtil.offset(Date(), DateField.MILLISECOND, delayTime.toInt())
                                })
                            } ?: run {
                                save(UserChannelFunction().apply {
                                    userId = ProfileHolder.getProfile().id.toLong()
                                    channelId = it.channelId
                                    functionId = it.functionId
                                })
                            }
                        }
                    }
            }
    }
}